package org.thanos.demo.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.epoll.Epoll;
import io.netty.channel.epoll.EpollEventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.ResourceLeakDetector;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.thanos.demo.handler.DemoHandler;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

@Slf4j
public class NettyTcpServer {

    @Value("${netty.port}")
    private int port;

    @Autowired
    private DemoHandler demoHandler;

    /**
     * 启动Server
     *
     * @throws InterruptedException
     */
    public void start() throws InterruptedException {
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup(), workerGroup())
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 1024)
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .childOption(ChannelOption.AUTO_READ, false)//不自动执行read
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        // 网络超时时间
                        socketChannel.pipeline().addLast(new IdleStateHandler(15, 0, 0, TimeUnit.MINUTES));
                        //解码格式
                        socketChannel.pipeline().addLast(new DelimiterBasedFrameDecoder(2048, Unpooled.copiedBuffer("$_$".getBytes(StandardCharsets.UTF_8))));
                        socketChannel.pipeline().addLast(new StringEncoder(StandardCharsets.UTF_8));
                        socketChannel.pipeline().addLast(new StringDecoder(StandardCharsets.UTF_8));
                        // 处理接收到的请求
                        socketChannel.pipeline().addLast(demoHandler); // 这里相当于过滤器，可以配置多个
                    }
                });
        ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.PARANOID);//内存泄漏检测 开发推荐PARANOID 线上SIMPLE
        ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
        channelFuture.channel().closeFuture().sync();
        if (channelFuture.isSuccess()) {
            log.info("TCP服务启动完毕, port:{}", this.port);
        }
    }

    /**
     * 销毁资源
     */
    public void destroy() {
        bossGroup().shutdownGracefully().syncUninterruptibly();
        workerGroup().shutdownGracefully().syncUninterruptibly();
        log.info("关闭成功");
    }

    /**
     * 负责TCP连接建立操作 绝对不能阻塞
     *
     * @return
     */
    private EventLoopGroup bossGroup() {
        int bossThreadsNum = 1;
        return Epoll.isAvailable() ? new EpollEventLoopGroup(bossThreadsNum) : new NioEventLoopGroup(bossThreadsNum);
    }

    /**
     * 负责Socket读写操作 绝对不能阻塞
     *
     * @return
     */
    private EventLoopGroup workerGroup() {
        int workerThreadsNum = Runtime.getRuntime().availableProcessors() << 1;
        return Epoll.isAvailable() ? new EpollEventLoopGroup(workerThreadsNum) : new NioEventLoopGroup(workerThreadsNum);
    }

}
